import {
	Base64
} from 'js-base64';
import Crypto from 'crypto-js';
import Base641 from 'crypto-js/enc-base64';

const GlobalData = {
	AliyunUrl: 'https://gxmanager.oss-cn-shenzhen.aliyuncs.com',
	OSSAccessKeyId: 'LTAI4G4eUeeA1927TvTeb193',
	signature: 'MXrz2Q1fqdGsmKKTZUA8aoxaRwzw6P'
}

// 相册悬照片
const PhotoOrVideo = (callBack, obj = { path: '', type: 0, index, count: 1 }) => {
	if (obj.type == 1) { // 选择图片
		uni.chooseImage({
			count: obj.count, // 默认9
			sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
			success(res) {
				solution(res.tempFilePaths[0], callBack, obj.type, obj.index);
			},
			fail() {
				uni.hideLoading()
			}
		})
	} else if (obj.type == 2) { // 选择视频
		uni.chooseVideo({
			count: 1,
			sourceType: ['camera'], // , 'album'
			success(res) {
				solution(res.tempFilePath, callBack, obj.type, obj.index);
			},
			fail() {
				uni.hideLoading()
			}
		})
	} else { // 直接传入地址上传
		solution(obj.path, callBack, obj.type, obj.index);
	}

}
const solution = (path, callBack, type, index) => {
	var policyText = {
		"expiration": "3020-01-01T12:00:00.000Z", // 设置该Policy的失效时间，超过这个失效时间之后，就没有办法通过这个policy上传文件了
		"conditions": [
			["content-length-range", 0, 1048576000] // 设置上传文件的大小限制
		]
	};

	var policyBase64 = Base64.encode(JSON.stringify(policyText))
	var bytes = Crypto.HmacSHA1(policyBase64, GlobalData.signature, {
		asBytes: true
	})
	var signature = Base641.stringify(bytes);
	// console.log(JSON.stringify(policyText))
	// console.log(policyBase64)
	// console.log(bytes)
	// console.log(signature)

	var myDate = new Date(), month = myDate.getMonth() + 1
	var ossPathYear = myDate.getFullYear()
	var ossPathMonth = 	month < 10 ? ('0' + month) : month
	var ossPathDay = myDate.getDate()
	var ossPathHours = myDate.getHours() < 12 ? 'AM' : 'PM'
	var pathArr = path.split('.')
	var fileRandName = Date.now() + "" + parseInt(Math.random() * 1000)
	var fileName = fileRandName + '.' + (pathArr.length >= 3 ? pathArr[3] : (type == 2 ? "mp4" : "jpg"))
	// #ifdef APP-PLUS
	var platform = 'app'
	// #endif
	// #ifdef MP-WEIXIN
	var platform = 'wxMiniProgram'
	// #endif
	// #ifdef H5
	var platform = 'h5'
	// #endif
	var fileKey = `fkyy_wx_${platform}_${ossPathYear}/${ossPathMonth}/${ossPathDay}/${ossPathHours}/${fileName}` // fkyy_wx_xxx_2021/01/01/AM/01.jpg
	uni.uploadFile({
		url: GlobalData.AliyunUrl,
		filePath: path,
		fileType: 'image',
		name: 'file',
		formData: {
			name: path,
			key: fileKey,
			policy: policyBase64,
			OSSAccessKeyId: GlobalData.OSSAccessKeyId,
			signature: signature,
			success_action_status: '200'
		},
		success: (uploadFileRes) => {
			// console.log(uploadFileRes.data);
		},
		fail: (msg) => {
			// console.log(msg);
		},
		complete(uploadFileRes) {
			if (uploadFileRes.statusCode === 200) {
				const url = GlobalData.AliyunUrl + "/" + fileKey
				if (callBack) callBack(url, index, type)
			}
		}
	});
}

export default {
	PhotoOrVideo
}
